package common

import (
	"encoding/json"
	"reflect"
)

func IsContain(obj interface{}, target interface{}) bool {
	targetValue := reflect.ValueOf(target)

	switch reflect.TypeOf(target).Kind() {
	case reflect.Slice, reflect.Array:
		for i := 0; i < targetValue.Len(); i++ {
			if targetValue.Index(i).Interface() == obj {
				return true
			}
		}
	case reflect.Map:
		if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {
			return true
		}
	}

	return false
}

func GetKeysOfMap(m interface{}) []string {
	mValue := reflect.ValueOf(m)
	switch reflect.TypeOf(mValue).Kind() {
	case reflect.Map:
		keys := make([]string, len(mValue.MapKeys()))
		for key := range mValue.MapKeys() {
			keys = append(keys, mValue.MapKeys()[key].String())
		}
		return keys
	default:
		return nil
	}
}

func GetFieldValueOfObj(obj interface{}, key string) interface{} {
	t := reflect.TypeOf(obj)
	v := reflect.ValueOf(obj)
	for i := 0; i < t.NumField(); i++ {
		value := v.Field(i).Interface()
		if reflect.TypeOf(value).Kind() == reflect.Struct {
			result := GetFieldValueOfObj(value, key)
			if result != nil {
				return result
			}
		} else {
			if t.Field(i).Name == key {
				return value
			}
		}
	}
	return nil
}

func ToJson(m interface{}) string {
	myJson, err := json.Marshal(m)
	if err != nil {
		panic(err)
	}
	return string(myJson)
}
